<!DOCTYPE html>
<html lang="en">
<head>

    <!-- Use correct character set. -->
    <meta charset="utf-8">
    <!-- Tell IE to use the latest, best version (or Chrome Frame if pre-IE11). -->
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <!-- Make the application on mobile take up the full browser screen and disable user scaling. -->
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
    <title>Cesium Viewer</title>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="../cesium/Build/Cesium/Widgets/widgets.css" media="screen">
    <script  src="../cesium/Build/Cesium/Cesium.js"></script>

	<style>
		html {
		    height: 100%;
		}
		
		body {
		    height: 100%;
		    width: 100%;
		    margin: 0;
		    overflow: hidden;
		    padding: 0;
		    background: #000;
		}
		
		.fullWindow {
		    position: absolute;
		    top: 0;
		    left: 0;
		    height: 100%;
		    width: 100%;
		    margin: 0;
		    overflow: hidden;
		    padding: 0;
		    font-family: sans-serif;
		}
		
		.loadingIndicator {
		    display: block;
		    position: absolute;
		    top: 50%;
		    left: 50%;
		    margin-top: -33px;
		    margin-left: -33px;
		    width: 66px;
		    height: 66px;
		    background-position: center;
		    background-repeat: no-repeat;
		    background-image: url(Images/ajax-loader.gif);
		}
	
	</style>	
              
</head>
<body style="background: #000;">
    <div id="cesiumContainer" class="fullWindow"></div>
    <div id="loadingIndicator" class="loadingIndicator"></div>
</body>
<script>
document.ontouchmove = function(e) {e.preventDefault()};

var extent = Cesium.Rectangle.fromDegrees(13.315944699999177, 52.50384029999778, 13.322660735671015, 52.50819486106173);

Cesium.Camera.DEFAULT_VIEW_FACTOR=0;
Cesium.Camera.DEFAULT_VIEW_RECTANGLE = extent;

Cesium.DataSourceDisplay.defaultVisualizersCallback = function (scene, dataSource) {
    var entities = dataSource.entities;
    return [
        new Cesium.ModelVisualizer(scene, entities)
    ];
};

var viewer;
try {
    
	viewer = new Cesium.Viewer('cesiumContainer', {
		"timeline":false,
		"animation":false, 
		"baseLayerPicker":true,
		"geocoder":false,									
		"infoBox":false,
		"sceneModePicker":false,
		"selectionIndicator":false,
		"navigationHelpButton":true,
		"navigationInstructionsInitiallyVisible":true,
		"scene3DOnly":true });		 
} catch (exception) {
	document.getElementById("loadingIndicator").style.display = 'none';    
    console.error(exception);
    if (!document.querySelector('.cesium-widget-errorPanel')) {
        window.alert(exception);
    }
}


var canvas =  viewer.scene.canvas;

var scene = viewer.scene;


var dataSources = {};

var getTileStructure = function(){    	
	var tilesToRender = scene.globe._surface._tilesToRender;
	var tiles = [];
	for(var i = 0; i < tilesToRender.length; i++){
		if(tilesToRender[i].level >= maxLevel){
    		var tile = {
    					bbox:[tilesToRender[i].rectangle.west,
    					      tilesToRender[i].rectangle.south,
    					      tilesToRender[i].rectangle.east,
    					      tilesToRender[i].rectangle.north], 
    					level:tilesToRender[i]._level, 
    					distance:tilesToRender[i]._distance    		
    		}
    		tiles.push(tile);
		}
	}    	
	return tiles;
}
var worker = new Worker('TilesWorkerTiled.js');

worker.addEventListener('message', function(e) {
	var data = e.data;
	  switch (data.cmd) {
	    case 'add':
	    	var id =  data.data.id;
	    	var url = data.data.url;
	    	var x = data.data.x;
	    	var y = data.data.y;
	    	var z = data.data.z;
    		var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
        		    Cesium.Cartesian3.fromDegrees(x, y, 0.0));
    		dataSources[id] = scene.primitives.add(Cesium.Model.fromGltf({
    		    	url : url,
    		    	modelMatrix : modelMatrix,		 
    		    	scale : 1, 
					allowPicking:true
    			})				
			);
	    	break;
	    case 'remove':
	    	var ids =  data.ids;
	    	var counter = 0;
	    	for(var i = 0; i < ids.length; i++){
	    		var id = ids[i];
    	    	if(dataSources.hasOwnProperty(id)){
    	    		scene.primitives.remove(dataSources[id]);
    	    		delete dataSources[id];
    	    		counter++
    	    	}
	  		}
	    	break;
	  }    
}, false);
   
worker.postMessage({'cmd':'initialize', 'url':'http://hosting.virtualcitysystems.de/demos/berlin/cesium/data/collada.json'});

viewer.scene.postRender.addEventListener(function(scene, time)  {
	worker.postMessage({'cmd':'postRender'});
});

var camera = viewer.camera;
var removeEnd = camera.moveEnd.addEventListener(function() {
	console.log("cameraListenerEnd");
	worker.postMessage({'cmd':'tileStructureChanged', "tiles":getTileStructure(), "maxLevel":maxLevel, "maxModels":maxModels});
});


var showLoadError = function(name, error) {
    var title = 'An error occurred while loading the file: ' + name;
    var message = 'An error occurred while loading the file, which may indicate that it is invalid.  A detailed error report is below:';
    viewer.cesiumWidget.showErrorPanel(title, message, error);
};


// add copyright information for berlin model
viewer.scene.frameState.creditDisplay.addDefaultCredit(new Cesium.Credit('EFRE', 'http://81.169.167.246/images/opendata/efre.png', 'http://www.berlin.de/sen/wirtschaft/gruenden-und-foerdern/europaeische-strukturfonds/'));
viewer.scene.frameState.creditDisplay.addDefaultCredit(new Cesium.Credit('EU', 'http://81.169.167.246/images/opendata/EU_efre_weiss.png', 'http://www.berlin.de/sen/wirtschaft/gruenden-und-foerdern/europaeische-strukturfonds/'));
viewer.scene.frameState.creditDisplay.addDefaultCredit(new Cesium.Credit('Im Auftrag der Senatsverwaltung für Wirtschaft, Technologie und Forschung, gefördert aus dem Europäischen Fonds für Regionale Entwicklung (EFRE).'));

	

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var maxLevel = parseInt(getParameterByName("maxLevel"));
var maxModels = parseInt(getParameterByName("maxModels"));

if(isNaN(maxLevel)){
	maxLevel = 16;
}
console.log("Set MaxLevel to " + maxLevel);
if(isNaN(maxModels)){
	maxModels = 500;
}
console.log("Set MaxModels to " + maxModels);

loadingIndicator.style.display = 'none';
</script>
</html>